package com.youmingxing.activity.selfInfo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.bean.User;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.StringUtil;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * @author chihiro(xuchang)
 * @since 2015-10-12
 */

public class ModifyAddressActivity extends BaseActivity {
    JSONArray citys;
    ListView listAddress;
    AddressAdapter addressAdapter;
    ArrayList<String> address;
    int currentPage;
    int option;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_modifty_address);
        Bundle bundle = getIntent().getExtras();
        option = bundle.getInt("option");
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            setResult(Activity.RESULT_OK, data);
            finish();
        }
    }

    private void initView() {
        listAddress = (ListView) findViewById(R.id.list_address);
        try {
            Bundle bundle = this.getIntent().getExtras();
            if (bundle!=null &&bundle.getString("city")!=null) {
                //不是第一个页面,从上一个页面获取数据
                JSONObject city = new JSONObject(bundle.getString("city"));
                citys = city.getJSONArray("sub");
                address = bundle.getStringArrayList("address");
                currentPage = bundle.getInt("current_page") + 1;
            } else {
                //新建第一个页面,获取assert中的city.json
                InputStream is = null;
                is = getResources().openRawResource(R.raw.city);
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                String json = new String(buffer, "utf-8");
                citys = new JSONArray(json);
                address = new ArrayList<>();
                currentPage = 1;
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        addressAdapter = new AddressAdapter();
        listAddress.setAdapter(addressAdapter);
        listAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ModifyAddressActivity.this, ModifyAddressActivity.class);
                JSONObject city = (JSONObject) citys.opt(position);
                if (city.has("sub") && city.optJSONArray("sub").length()!=0) {
                    //点击一个还有下一级页面的城市
                    intent.putExtra("city", city.toString());
                    if (address.size() == currentPage) {
                        address.remove(currentPage - 1);
                    }
                    address.add(city.optString("name"));
                    intent.putExtra("address", address);
                    intent.putExtra("option", option);
                    intent.putExtra("current_page", currentPage);
                    startActivityForResult(intent, 0);
                } else {
                    //点击最后一级页面
                    if (address.size() == currentPage) {
                        address.remove(currentPage - 1);
                    }
                    address.add(city.optString("name"));
                    String finalAddress = StringUtil.listToString(address);
                    SelfInfoApi.modifyUserProfile(User.Info.values()[option].toString(), finalAddress, new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            if (response.optJSONObject("data").optInt("result") == 1) {
                                showToast("修改成功");
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            showToast("修改失败");
                        }
                    });
                    intent.putExtra("address", finalAddress);
                    intent.putExtra("option", option);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

            }
        });

    }

    private static class ViewHolder {
        TextView addressText;
        View arrowImage;
        View divider;
    }

    private class AddressAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return citys.length();
        }

        @Override
        public Object getItem(int position) {
            return 0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            return position != 0 && super.isEnabled(position);
        }

        @Override
        public android.view.View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(ModifyAddressActivity.this, R.layout.list_item_modify_info, null);
                holder = new ViewHolder();
                convertView.findViewById(R.id.option_value_text).setVisibility(View.INVISIBLE);
                convertView.setMinimumHeight(50);

                holder.addressText = (TextView) convertView.findViewById(R.id.option_text);
                holder.arrowImage = convertView.findViewById(R.id.right_arrow);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            JSONObject city = (JSONObject) citys.opt(position);
            holder.addressText.setText(city.optString("name"));
            if (city.has("sub") && city.optJSONArray("sub").length()!=0 && position!=0) {
                holder.arrowImage.setVisibility(View.VISIBLE);
            } else {
                holder.arrowImage.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }
    }
}
